package com.jule.teenpatti.mail.network.handler;

import com.jule.teenpatti.mail.network.protocol.ClientReq;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class IoHandler extends SimpleChannelInboundHandler<ClientReq> {

    public static final AttributeKey<String> IP = AttributeKey.valueOf("ip");
    //public static final AttributeKey<PlayerInfo> ATTACH_PLAYER = AttributeKey.valueOf("player");

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        String ip = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
        ctx.channel().attr(IP).set(ip);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ClientReq request) throws Exception {
        if (request != null) {
            request.run();
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (IdleStateEvent.class.isAssignableFrom(evt.getClass())) {
            IdleStateEvent event = (IdleStateEvent) evt;
            if (event.state() == IdleState.READER_IDLE) {
                ctx.close();
            } else if (event.state() == IdleState.WRITER_IDLE) {
                ctx.close();
            } else if (event.state() == IdleState.ALL_IDLE) {
                ctx.close();
            }
        }
    }
}
